package com.student.course.service.impl;

import com.student.common.entity.Course;
import com.student.course.service.CourseService;
import com.student.course.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;

/**
 * 课程服务实现类
 * 
 * @author student
 * @date 2025
 */
@Service
public class CourseServiceImpl implements CourseService {
    
    @Autowired
    private CourseRepository courseRepository;
    
    @Override
    public Page<Course> getCourseList(Pageable pageable, String courseName, String department, String courseType, String courseId, String status) {
        if (StringUtils.hasText(courseName) || StringUtils.hasText(department) || StringUtils.hasText(courseType) || 
            StringUtils.hasText(courseId) || StringUtils.hasText(status)) {
            return courseRepository.findByConditions(courseName, department, courseType, courseId, status, pageable);
        }
        return courseRepository.findAll(pageable);
    }
    
    @Override
    public Course getCourseById(String courseId) {
        return courseRepository.findById(courseId).orElse(null);
    }
    
    @Override
    public boolean addCourse(Course course) {
        if (courseRepository.existsById(course.getCourseId())) {
            return false;
        }
        
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        // 如果前端没有设置状态，默认为"开设"
        if (course.getStatus() == null || course.getStatus().isEmpty()) {
            course.setStatus("开设");
        }
        courseRepository.save(course);
        return true;
    }
    
    @Override
    public boolean updateCourse(Course course) {
        if (!courseRepository.existsById(course.getCourseId())) {
            return false;
        }
        
        // 获取现有课程信息，保留创建时间
        Course existingCourse = courseRepository.findById(course.getCourseId()).orElse(null);
        if (existingCourse != null) {
            course.setCreateTime(existingCourse.getCreateTime());
        }
        
        course.setUpdateTime(LocalDateTime.now());
        courseRepository.save(course);
        return true;
    }
    
    @Override
    public boolean deleteCourse(String courseId) {
        if (!courseRepository.existsById(courseId)) {
            return false;
        }
        
        // 检查是否有选课记录
        // 这里可以调用选课服务检查，简化处理直接删除
        courseRepository.deleteById(courseId);
        return true;
    }
    
    @Override
    public Page<Course> getCoursesByTeacherId(Pageable pageable, String teacherId) {
        return courseRepository.findByTeacherId(teacherId, pageable);
    }
    
    @Override
    public long getCourseCount() {
        return courseRepository.count();
    }
}
